//自己实现一个阻塞队列
//1.先实现一个普通的队列  2.加上线程安全  3.加上阻塞功能
class MyPriorityBlockingQueue {
    private int[] items = new int[1000];
    // [head,tail） 是有效元素
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;
    volatile private Object locker = new Object();
    synchronized public void put(int val) throws InterruptedException {
        //加上阻塞功能 ：当队列满就等待队列出一个元素
        while (size == items.length - 1) {
            this.wait();
        }
        //把新的元素放入到队列中
        items[tail] = val;
        tail++;
        //如果队列是满的，就让tail从头开始
        while (tail == items.length - 1) {
            tail = head;
        }
        size++;
        this.notify();
    }

    synchronized public Integer take() throws InterruptedException {
        while (size == 0) {
            //return null;
            this.wait();
        }
        int value = items[head];
        head++;
        if (head == items.length) head = 0;
        size--;
        this.notify();
        return value;
    }
}
public class ThreadDemo28Practice {
    public static void main(String[] args) {
        //首先要有一个阻塞队列用来任务的阻塞，基于生产者消费者模型
        MyBlockingQueue queue = new MyBlockingQueue();

        //消费者
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    int value = queue.take();
                    System.out.println("消费元素：" + value);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //生产者
        Thread t1 = new Thread(() -> {
            int value = 0;
            while (true) {
                try {
                    queue.put(value);
                    System.out.println("生产元素：" + value);
                    value++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
